<?php
/**
 * @package QFinance
 */
/**
 * Class that configure, check and execute remote actions
 */
class RemotingService {	
	/**
	 * Remoting constructor
	 */
	public function RemotingService() {}
	
	/**
	 * Configure, check and execute remote action
	 */
	public function doRemoting() {		
		ExtDirect::$namespace = "QFinance.Remoting";
		ExtDirect::$descriptor= "QFinance.Remoting.API";
		ExtDirect::$url = $_SERVER['PHP_SELF'] . "?doRemoting";
		ExtDirect::$count_only_required_params = true;
		ExtDirect::$debug = true;
		ExtDirect::$authorization_function = 'RemotingService::remoteAuthorization';

		if (DeveloperService::$remotingDelay)
			usleep(rand(1,1000)*1000);				
		
		$securityService = SecurityService::getInstance();
		$classArray = array();
		foreach ($securityService->getActions() as $action)
			array_push($classArray, $action->actionName);

		ExtDirect::provide( $classArray );
	}
	
	/**
	 * Do authorization on remote call
	 * @param ExtDirectAction $extDirectAction ExtDirect action
	 * @return boolean If action is authorized or not.
	 */
	public static function remoteAuthorization( $extDirectAction ) {
		$securityService = SecurityService::getInstance();

		if ($extDirectAction->action != "DeveloperServiceAction") {				
			DeveloperService::log("Called action '" . $extDirectAction->action . "' method '" . $extDirectAction->method . "'");
		}
											
		if ($securityService->actionNeedAuthorization( $extDirectAction->action )) {
			if (DeveloperService::$remotingDeny || (DeveloperService::$remotingRandomDeny && mt_rand(0,5) == 1)) {
				return false;
			} else {
				if (!DeveloperService::$bypassLogin) {
					$securityService = SecurityService::getInstance();
					return $securityService->isLogged();
				}
			}
		} else {
			return true;	
		}	
	}
}